package com.seeyon.ctp.rest.resources;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.seeyon.apps.cxgd.kit.HttpKit;
import com.seeyon.apps.cxgd.kit.LogKit;
import com.seeyon.apps.cxgd.kit.SameBusinessTripKit;
import com.seeyon.apps.cxgd.kit.StrKit;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.formula.FormulaUtil;
import com.seeyon.ctp.common.log.CtpLogFactory;
import org.apache.commons.logging.Log;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Path("jssdk")
@Consumes(MediaType.APPLICATION_JSON)
@Produces({MediaType.APPLICATION_JSON})
public class CustomSSOResources extends BaseResource {

    private static final Log log = CtpLogFactory.getLog(CustomSSOResources.class);
    @Context
    private HttpServletRequest request;

    @Context
    private HttpServletResponse response;

    @GET
    @Path("oa/sso/trip")
    public Response acquireSSOAuthCode(Map<String, Object> param) {
        try {
            String plat = StrKit.str(request.getParameter("plat"));
            log.info("pc端或移动端跳转标识:" + plat);
            String same_business_trip_url = StrKit.str(FormulaUtil.getVar("same_business_trip_url"));
            String secret = StrKit.str(FormulaUtil.getVar("tcSecret"));
            String loginName = AppContext.getCurrentUser().getLoginName();
            long memberId = AppContext.getCurrentUser().getId();
            Map<String, Object> map = new HashMap<String, Object>();
            String accessToken = SameBusinessTripKit.getSameBusinessTripToken();
            map.put("accessToken", accessToken);
            map.put("isEncrypt", false);
            map.put("random", UUID.randomUUID().toString());
            map.put("timestamp", System.currentTimeMillis());
            Map<String, Object> param_map = new HashMap<String, Object>();
            if ("test3".equals(loginName)) {
                param_map.put("outEmployeeId", "test001");
            } else {
                param_map.put("outEmployeeId", memberId);
            }
            if ("pc".equals(plat)) {
                param_map.put("plat", 0);
            } else {
                param_map.put("plat", 1);
            }

            param_map.put("entrance", 0);
            param_map.put("travelType", 1);
            map.put("param", param_map);
            String data_json = JSON.toJSONString(map);
            String dataMd5 = SameBusinessTripKit.stringToMD5(data_json);
            String signStr = dataMd5 + secret;
            String sign = SameBusinessTripKit.stringToMD5(signStr);
            String url = same_business_trip_url + "/openapi/api/Employee/SSO?sign=" + sign;
            String result = HttpKit.httpsPost(url, new HashMap<String, Object>(), data_json);
            log.info("同程单点登录接口返回信息:" + result);
            LogKit.addLog(AppContext.getCurrentUser().getName(), "同程单点登录接口", data_json, result);
            JSONObject jsonObject = JSONObject.parseObject(result);
            String success = StrKit.str(jsonObject.get("success"));
            if ("true".equals(success)) {
                String redirectUrl = StrKit.str(jsonObject.get("redirectUrl"));
                response.sendRedirect(redirectUrl);
            } else {
                String errorMessage = StrKit.str(jsonObject.get("errorMessage"));
                return ok(errorMessage);
            }
        } catch (Exception e) {
            log.error("单点登录接口异常信息:", e);
        }
        return null;
    }

}